import Icon from '@/components/Icon';
import classNames from 'classnames';
import { useRouter } from 'next/dist/client/router';
import Link from 'next/link';
import { useState } from 'react';
import classes from './Side.module.css';

type Props = {
  files: FileItem[];
};

const Item: React.FC<{ item: FileItem; level?: number }> = ({
  item,
  level = 1,
}) => {
  const { asPath } = useRouter();
  const [expend, setExpend] = useState(true);
  const url = `/doc/${encodeURIComponent(item.filePath)}`;
  const link = (
    <a
      style={{ paddingLeft: level * 14 }}
      className={classNames(
        'ellipse',
        classes.item,
        asPath === url && classes.active
      )}
      onClick={() => {
        if (item.children) {
          setExpend(!expend);
        }
      }}
    >
      {item.fileName}
      {item.children && (
        <Icon
          className={classNames(classes.icon, !expend && classes.rotate)}
          icon="icon-sort-down"
        />
      )}
    </a>
  );
  return (
    <>
      {item.children ? link : <Link href={url}>{link}</Link>}
      {item.children &&
        expend &&
        item.children.map((t) => (
          <Item key={t.filePath} item={t} level={level + 1} />
        ))}
    </>
  );
};

const Side: React.FC<Props> = ({ files }) => {
  return (
    <div className={classes.wrap}>
      {files.map((item) => (
        <Item key={item.filePath} item={item} />
      ))}
    </div>
  );
};

export default Side;
